<template>
  <div class="div">
    <n-layout position="absolute">
      <n-form ref="formRef" inline :label-width="80" class="nform">
        <n-form-item label="年级(一年级---高三)" path="user.level">
          <n-select v-model:value="user.level" :options="generalOptions" placeholder="" />
        </n-form-item>
        <n-form-item label="学科(语数英)" path="user.subjectId">
          <n-select v-model:value="user.subjectId" :options="subjectOptions" placeholder="" />
        </n-form-item>
        <n-form-item>
          <n-button @click="handleValidateClick">查询</n-button>
        </n-form-item>
      </n-form>
      <n-layout class="layout" position="absolute" has-sider style="top: 64px">
        <n-layout-sider bordered content-style="padding: 24px;">
          用户名：&nbsp;<n-tag type="info">{{ userName }}</n-tag
          ><br />
          倒计时：
          <n-tag type="info">
            <span style="font-variant-numeric: tabular-nums">
              <n-countdown
                ref="countdown"
                :duration="1800000"
                :active="active"
                :on-finish="onFinish"
              />
            </span> </n-tag
          ><br />
          <span v-if="showAnswer == true"
            >总分:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <n-tag type="info">
              <span>&nbsp;&nbsp;{{ totalScore }}</span>
            </n-tag>
          </span>
        </n-layout-sider>
        <n-layout vertical content-style="padding: 24px;" class="lout">
          <div v-if="pageValue != null">
            <div v-for="(data, index) in pageValue" :key="data.id" class="sdiv">
              <p style="font-weight: 700">
                第{{ index + 1 }}题:<span>&nbsp;&nbsp;</span>{{ data.topic
                }}<span>（{{ data.score }}分</span>
              </p>
              <n-space>
                <n-radio
                  v-show="pageValue[index].typeA != null"
                  v-model:value="pageValue[index].typeA"
                  :checked="checkedValue[index] === pageValue[index].typeA"
                  :disabled="disabled == true"
                  @change="handleChange(pageValue[index].typeA, index)"
                >
                  {{ data.typeA }}
                </n-radio>
                <n-radio
                  v-show="pageValue[index].typeB != null"
                  v-model:value="pageValue[index].typeB"
                  :checked="checkedValue[index] === pageValue[index].typeB"
                  :disabled="disabled == true"
                  @change="handleChange(pageValue[index].typeB, index)"
                >
                  {{ data.typeB }}
                </n-radio>
                <n-radio
                  v-show="pageValue[index].typeC != null"
                  v-model:value="pageValue[index].typeC"
                  :checked="checkedValue[index] === pageValue[index].typeC"
                  :disabled="disabled == true"
                  @change="handleChange(pageValue[index].typeC, index)"
                >
                  {{ data.typeC }}
                </n-radio>
                <n-radio
                  v-show="pageValue[index].typeD != null"
                  v-model:value="pageValue[index].typeD"
                  :checked="checkedValue[index] === pageValue[index].typeD"
                  :disabled="disabled == true"
                  @change="handleChange(pageValue[index].typeD, index)"
                >
                  {{ data.typeD }}
                </n-radio>
              </n-space>
              <n-tag
                v-if="showAnswer == true"
                :color="{ color: checkedValue[index] == data.answer ? 'green' : 'red' }"
              >
                <span style="font-weight: 500">
                  正确答案:<span>&nbsp;&nbsp;</span>{{ data.answer }} <br />解析:<span
                    >&nbsp;&nbsp;</span
                  >{{ data.parse }}
                </span>
              </n-tag>
            </div>
            <n-button type="success" class="nsubmit" @click="handleSubmit">提交</n-button>
          </div>
        </n-layout>
      </n-layout>
    </n-layout>
  </div>
</template>

<script setup lang="ts">
  import { defineComponent, onMounted, ref, reactive } from 'vue'
  import {
    NLayout,
    NLayoutSider,
    NH2,
    NForm,
    NFormItem,
    NSelect,
    NButton,
    NTag,
    useMessage,
    NSpace,
    NRadio,
    NRadioGroup,
    NCountdown,
    CountdownInst
  } from 'naive-ui'
  import store from '../../store/dailyStore/index'
  import userStore from '../../store/userStore/index'
  import userApi from '../../api/user'

  const userName = sessionStorage.getItem('userName')
  const id = ref(null)
  const useuserStore = userStore()
  const message = useMessage()
  const user = ref({
    subjectId: '',
    level: ''
  })
  let checkedValue = reactive([] as any[])
  let rightValue = reactive([] as any[])
  let pageValue = ref()
  const dailyStore = store()
  const showAnswer = ref(false)
  const active = ref(false)
  const countdownRef = ref<CountdownInst | null>()
  const countdown = countdownRef
  const disabled = ref(false)
  const cutScreen = ref(3)
  //总分
  let totalScore = ref(0)
  onMounted(() => {
    //userName = sessionStorage.getItem('userName')
    //获取登录ID
    useuserStore.getUserInfo().then(({ data }) => {
      id.value = data.id
    })
  })
  const pageHidden = () => {
    if (document.visibilityState === 'hidden') {
      cutScreen.value--
      if (cutScreen.value != 0) {
        message.error('测试期间最多可切屏3次，还剩' + cutScreen.value + '次切屏机会')
      }
      if (cutScreen.value <= 0) {
        handleSubmit()
        console.log('自动提交')
      }
    }
  }
  //查询
  const handleValidateClick = () => {
    if (user.value.level == '') {
      message.warning('请选择年级')
      return
    }
    if (user.value.subjectId == '') {
      message.warning('请选择学科')
      return
    }
    dailyStore.getContentList(user.value, id.value).then(({ data }) => {
      pageValue.value = data
      active.value = true
      //用于重新点击查询时隐藏答案
      showAnswer.value = false
      //重置倒计时时间
      handleReset()
      //点击查询后radio可修改
      disabled.value = false
      //重置总分
      totalScore.value = 0
    })
    // 监听页面可见性
    window.addEventListener('visibilitychange', pageHidden)
    cutScreen.value = 3
  }
  const handleChange = (val: any, index: any) => {
    showAnswer.value = false
    checkedValue[index] = val
  }
  //提交
  const handleSubmit = () => {
    //点击提交后radio不可修改
    disabled.value = true
    showAnswer.value = true
    active.value = false
    checkedValue.forEach((val, idx) => {
      if (pageValue.value[idx].answer == val) {
        totalScore.value += pageValue.value[idx].score
        rightValue.push(pageValue.value[idx].id)
      }
    })
    dailyStore.addRecord(rightValue)
    //移除防切屏
    window.removeEventListener('visibilitychange', pageHidden)
  }
  const onFinish = () => {
    message.warning('您的答题时间已到，将会自动提交试卷！！！')
    handleSubmit()
  }
  //重置倒计时
  const handleReset = () => {
    countdownRef.value?.reset()
  }
  const generalOptions = [
    {
      label: '一年级',
      value: 1
    },
    {
      label: '二年级',
      value: 2
    },
    {
      label: '三年级',
      value: 3
    },
    {
      label: '四年级',
      value: 4
    },
    {
      label: '五年级',
      value: 5
    },
    {
      label: '六年级',
      value: 6
    },
    {
      label: '初一',
      value: 7
    },
    {
      label: '初二',
      value: 8
    },
    {
      label: '初三',
      value: 9
    },
    {
      label: '高一',
      value: 10
    },
    {
      label: '高二',
      value: 11
    },
    {
      label: '高三',
      value: 12
    }
  ]
  const subjectOptions = [
    {
      label: '语文',
      value: 1
    },
    {
      label: '数学',
      value: 2
    },
    {
      label: '英语',
      value: 3
    }
  ]
</script>
<style scoped>
  html,
  body,
  .div {
    height: 100%;
  }
  .lout {
    background-color: #eeeeee;
  }
  .nform {
    position: absolute;
    left: 30%;
  }
  .sdiv {
    height: 90px;
  }
  .nsubmit {
    position: relative;
    left: 35%;
    width: 150px;
  }
</style>
